// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.superlists.model;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

/**
 * JSON Utilities.
 *
 * @author sven@google.com (Sven Mawson)
 */
public class JsonUtil {

  /** Parses a bean from JSON. */
  public static <T> T fromJson(String json, Class<T> clazz) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    return gson.fromJson(json, clazz);
  }

  /**
   * Parses a type from JSON. Useful for parameterized types like maps.
   */
  public static <T> T fromJson(String json, Type type) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    return gson.fromJson(json, type);
  }

  /** Renders a bean as JSON. */
  public static String toJson(Object obj) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    return gson.toJson(obj);
  }
}
